<template>
 <a-upload
    v-model:file-list="fileList"
    name="uploadFile"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="baseURL+'/file/upload/'"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <img style="width: 100%;" v-if="imageUrl" :src="imageUrl" alt="avatar" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>
<script setup>
import {ref} from "vue"
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
const baseURL = import.meta.env.VITE_APP_API_URL;
const props = defineProps({
    value: [Number, Array],
  });

  const emit = defineEmits(['update:value']);

const fileList = ref([])
const imageUrl = ref(props.value)
const loading = ref(false);
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (base64Url) => {
          imageUrl.value = base64Url;
          let res= info.file.response
          emit('update:value', res.data);
          loading.value = false;
        });
      }
      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    }

    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 < 40;
      if (!isLt2M) {
        message.error('Image must smaller than 40KB!');
      }
      return isJpgOrPng && isLt2M;
    };


</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px !important;
  height: 128px !important;
}
.ant-upload-select-picture-card i {
  font-size: 32px !important;
  color: #999 !important;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px !important;
  color: #666 !important;
}
</style>
